"use client";
import {
  List,
  EditButton,
  ShowButton,
  DeleteButton,
  useTable,
} from "@refinedev/antd";
import { Space, Table } from "antd";
import { useEffect, useState } from "react";

/**
 * 角色列表页面组件
 * 展示角色列表并支持分页、排序和操作按钮
 */
export default function RoleList() {
  const [datas, setDatas] = useState<any[]>([]);
  const [total, setTotal] = useState(0);
  const { tableProps,setCurrent,setPageSize, tableQueryResult } = useTable({
    resource: "system/role/list",
    syncWithLocation: true,
    pagination: {
      current: 1,
    },
  });

  /**
   * 处理表格数据加载完成后的状态更新
   * 从表格数据中提取角色列表和总条数
   */
  useEffect(() => {
    console.log(tableProps);
    const res = tableProps?.dataSource as any;
    if (res && res.data) {
      const { list, total } = res.data;
      setDatas(list);
      setTotal(total);
    }
  }, [tableProps?.dataSource]);
  
  return (
    <List>
      <Table dataSource={datas} rowKey="role_id" loading={tableProps?.loading} pagination={{
      showTotal: (total, range) => `总共 ${total} 条`,
      pageSize: 10,
      total: total,
      onChange: (page, pageSize) => {
        console.log(page,pageSize);
        setCurrent(page);
        setPageSize(pageSize);
      },
    }}>
        <Table.Column dataIndex="role_id" title={"角色ID"} />
        <Table.Column dataIndex="role_name" title={"角色名称"} />
        <Table.Column dataIndex="role_key" title={"权限字符串"} />
        <Table.Column dataIndex="role_sort" title={"显示顺序"} />
        <Table.Column 
          dataIndex="status" 
          title={"状态"}
          render={(status) => (
            <span style={{ color: status === '0' ? '#52c41a' : '#ff4d4f' }}>
              {status === '0' ? '正常' : '停用'}
            </span>
          )}
        />
        <Table.Column dataIndex="remark" title={"备注"} />
        <Table.Column
          title={"操作"}
          dataIndex="actions"
          render={(_, record) => {
            const isProtected = record.role_id === 1;
            return (
              <Space>
                <EditButton 
                  hideText 
                  size="small" 
                  recordItemId={record.role_id}
                  disabled={isProtected}
                  title={isProtected ? "超级管理员角色不可编辑" : "编辑"}
                />
                <ShowButton 
                  hideText 
                  size="small" 
                  recordItemId={record.role_id}
                  title="查看"
                />
                <DeleteButton 
                  hideText 
                  size="small" 
                  recordItemId={record.role_id}
                  disabled={isProtected}
                  title={isProtected ? "超级管理员角色不可删除" : "删除"}
                  onSuccess={() => {
                    // 刷新列表
                    tableQueryResult.refetch();
                  }}
                />
              </Space>
            );
          }}
        />
      </Table>
    </List>
  );
} 